#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>
#include "static.h"

void Widget::paintEvent(QPaintEvent*)
{
    int x = this->x();
    int y = this->y();
    int w = width();
    int h = height();

    QPainter painter(this);
    QPixmap map("");
    painter.drawPixmap(0,0,w,h,map);
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    qDebug()<<"test";
    {
        client = new QMQTT::Client(QHostAddress("192.168.28.37"),1883);
        client->setClientId("clientid");

        client->connectToHost();

        connect(client,SIGNAL(connected()),this,SLOT(doConnected()));

        connect(client,SIGNAL(subscribed(const QString&, const quint8)),\
                this,SLOT(doSubscribed(const QString&, const quint8)));

        connect(client,SIGNAL(received(QMQTT::Message)),\
                this,SLOT(doDataReceived(QMQTT::Message)));


    }

    {
        QObject::connect(ui->bedlight, SIGNAL(clicked()),
                           this, SLOT(bedlight()));
        QObject::connect(ui->bedairtemp, SIGNAL(valueChanged(int)),
                           this, SLOT(bedairtemp(int)));
        QObject::connect(ui->bedairswitch, SIGNAL(clicked()),
                           this, SLOT(bedairswitch()));
        QObject::connect(ui->bedtemperature, SIGNAL(clicked()),
                           this, SLOT(bedtemperature()));
        QObject::connect(ui->bedhumidity, SIGNAL(clicked()),
                           this, SLOT(bedhumidity()));


        QObject::connect(ui->livingtemperature, SIGNAL(clicked()),
                           this, SLOT(livingtemperature()));
        QObject::connect(ui->livinghumidity, SIGNAL(clicked()),
                           this, SLOT(livinghumidity()));
        QObject::connect(ui->livingill, SIGNAL(clicked()),
                           this, SLOT(livingill()));
        QObject::connect(ui->livinglight, SIGNAL(clicked()),
                           this, SLOT(livinglight()));
        QObject::connect(ui->livingalarm, SIGNAL(clicked()),
                           this, SLOT(livingalarm()));
        QObject::connect(ui->livingfan, SIGNAL(clicked()),
                           this, SLOT(livingfan()));


        QObject::connect(ui->modeBox, SIGNAL(activated(int)),
                         this, SLOT(mode(int)));
        QObject::connect(ui->timeBox, SIGNAL(valueChanged(int)),
                         this, SLOT(savetime(int)));
        QObject::connect(ui->refresh, SIGNAL(clicked()),
                         this, SLOT(refresh()));

 //       ui->living->setIcon(QIcon(":/tb/living.png"));
        ui->livingtemperature->setIcon(QIcon(":/tb/temp.png"));
        ui->livinghumidity->setIcon(QIcon(":/tb/hum.png"));
        ui->livingalarm->setIcon(QIcon(":/tb/alarm.png"));
        ui->livingfan->setIcon(QIcon(":/tb/fan.png"));
        ui->livingill->setIcon(QIcon(":/tb/ill.png"));
        ui->livinglight->setIcon(QIcon(":/tb/light.png"));

    }

}


void Widget::doConnected()
{
    qDebug()<<"doConnected";
    client->subscribe("/app/data/up");
    client->subscribe("/app/control/up");
    client->subscribe("/app/mode/up");
}

void Widget::doDataReceived(QMQTT::Message message)
{
    QString mes = QString(message.id())+" "+QString(message.qos())+" "+message.topic()+" "+message.payload()+"\n";
    QString str = message.payload();
   // qDebug()<<"mes="<<str;



    if(message.topic()=="/app/mode/up")
        Widget::modeup(message);
    else if(message.topic()=="/app/control/up")
        Widget::controlup(message);
    else
        Widget::dataup(message);
}

void Widget::doSubscribed(const QString& topic, const quint8 qos)
{
    qDebug()<<"doSubscribed = "<<topic;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::refresh()
{
    QString topicPub = "/app/data/down";
    QJsonObject obj1;    //创建json对象
    obj1.insert("limit", "all");   //添加键值
    obj1.insert("type", "1");
    obj1.insert("keys", 1);
    QJsonDocument doc(obj1);     //构造成文档
    QByteArray data=doc.toJson();   //转换成文本格式字符串
    qDebug()<<"刷新";
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget::mode(int modeval)
{
    qDebug()<<modeval;
    QString topicPub = "/app/mode/down";
    QJsonObject obj1;
    QJsonObject obj2;
    if(modeval == 0)
    {
        obj2.insert("type", 0);
    }
    else if(modeval ==1)
    {
        obj2.insert("type", 1);
        qDebug()<<"nihao1";
        obj2.insert("period",time);
    }
    else
    {
        obj2.insert("type", 2);
    }
    obj1.insert("data",obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget::savetime(int timeval)
{
    time = timeval;
    qDebug()<<time;
}

void Widget::bedairswitch()
{
    qDebug()<<"airswitch";
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 103);
    if(Static::airf ==0 )
    {
        obj2.insert("val",1);
    }
    else if(Static::airf == 1 )
    {
        obj2.insert("val",0);
    }
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}

void Widget::bedairtemp(int airtempval)
{
  //  qDebug()<<airtempval;
    QString s = QString::number(airtempval,10);
    ui->bedairt->setText(s);
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 104);
    obj2.insert("val", s);
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget::bedlight()
{
    qDebug()<<"light";
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 105);
    if(Static::bedl ==0 )
    {
        obj2.insert("val",1);
    }
    else if(Static::bedl ==1 )
    {
        obj2.insert("val",0);
    }
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}

void Widget::bedtemperature()
{
    qDebug()<<"bedtemperature";
    QString topicPub = "/app/data/down";
    QJsonObject obj1;
    QJsonObject obj2;
    QJsonArray versionArray;
    versionArray.append(101);
    obj1.insert("type", 1);
    obj1.insert("limit", "part");
    obj1.insert("keys", QJsonValue(versionArray));
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}


void Widget::bedhumidity()
{
    qDebug()<<"bedhumidity";
    QString topicPub = "/app/data/down";
    QJsonObject obj1;
    QJsonObject obj2;
    QJsonArray versionArray;
    versionArray.append(102);
    obj1.insert("type", 1);
    obj1.insert("limit", "part");
    obj1.insert("keys", QJsonValue(versionArray));
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}


void Widget:: livingtemperature()
{
    qDebug()<<"livingtemperature";
    QString topicPub = "/app/data/down";
    QJsonObject obj1;
    QJsonObject obj2;
    QJsonArray versionArray;
    versionArray.append(1);
    obj1.insert("type", 1);
    obj1.insert("limit", "part");
    obj1.insert("keys", QJsonValue(versionArray));
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget:: livinghumidity()
{
    qDebug()<<"livinghumidity";
    QString topicPub = "/app/data/down";
    QJsonObject obj1;
    QJsonObject obj2;
    QJsonArray versionArray;
    versionArray.append(2);
    obj1.insert("type", 1);
    obj1.insert("limit", "part");
    obj1.insert("keys", QJsonValue(versionArray));
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget:: livingill()
{
    qDebug()<<"livingill";
    QString topicPub = "/app/data/down";
    QJsonObject obj1;
    QJsonArray versionArray;
    versionArray.append(3);
    obj1.insert("limit", "part");
    obj1.insert("keys", QJsonValue(versionArray));
    obj1.insert("type", 1);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget:: livinglight()
{
    qDebug()<<"livinglight";
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 4);
    if(Static::livingl ==0 )
    {
        obj2.insert("val",1);
    }
    else if(Static::livingl ==1 )
    {
        obj2.insert("val",0);
    }
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget:: livingfan()
{
    qDebug()<<"livingfan";
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 6);
    if(Static::livingf ==0 )
    {
        obj2.insert("val",1);
    }
    else if(Static::livingf ==1 )
    {
        obj2.insert("val",0);
    }
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);
}
void Widget:: livingalarm()
{
    qDebug()<<"livingalarm";
    QString topicPub = "/app/control/down";
    QJsonObject obj1;
    obj1.insert("type", 2);
    QJsonObject obj2;
    obj2.insert("key", 5);
    if(Static::livinga ==0 )
    {
        obj2.insert("val",1);
    }
    else if(Static::livinga ==1 )
    {
        obj2.insert("val",0);
    }
    obj1.insert("data", obj2);
    QJsonDocument doc(obj1);
    QByteArray data=doc.toJson();
    QMQTT::Message msg(0, topicPub.toLatin1(), data);
    client->publish(msg);

}
void Widget::dataup(QMQTT::Message message)
{
    QJsonParseError jerr;
    QJsonDocument doc = QJsonDocument::fromJson(message.payload(), &jerr);
    if (doc.isNull()) //判断存储是不是空值
    {
        qDebug() << jerr.errorString();
        return ;
    }
    QJsonObject jroot = doc.object();    //转换成json对象
    QJsonValue Value = jroot.value("data"); //通过key得到value
    QJsonArray dataArr = Value.toArray();  //json数组
    for(int i=0;i<dataArr.count();i++)
    {
        QJsonValue dataValue = dataArr.at(i);
        QJsonObject valObj = dataValue.toObject();
        echo(valObj);
    }
}

void Widget::echo(QJsonObject valObj)
{
    QJsonValue key = valObj.value("key");
    qDebug()<<key.toInt();
    QJsonValue val = valObj.value("val");
    qDebug()<<val.toString();
    if(key.toInt() == 1)
    {
        ui->livietemp->setText(val.toString());
    }
    if(key.toInt() == 2)
    {
        ui->livihumidity->setText(val.toString());
    }
    if(key.toInt() == 3)
    {
        ui->liviill->setText(val.toString());
    }
    if(key.toInt() == 4)
    {
        if(val.toString() == "0")
        {
            ui->livilight->setText("关");
            Static::livingl = 0;
        }
        else
        {
            ui->livilight->setText("开");
            Static::livingl = 1;
        }
    }
    if(key.toInt() == 5)
    {
        if(val.toString() == "0")
        {
            ui->livialarm->setText("关");
            Static::livinga = 0;
        }
        else
        {
            ui->livialarm->setText("开");
            Static::livinga = 1;
        }
    }
    if(key.toInt() == 6)
    {
        if(val.toString() == "0")
        {
            ui->livifan->setText("关");
            Static::livingf = 0;
        }
        else
        {
            ui->livifan->setText("开");
            Static::livingf = 1;
        }
    }
    if(key.toInt() == 101)
    {
        ui->bedtemp->setText(val.toString());
    }
    if(key.toInt() == 102)
    {
        ui->bedhum->setText(val.toString());
    }
    if(key.toInt() == 103)
    {
        if(val.toString() == "0")
        {
            ui->bedairw->setText("关");
            Static::airf = 0;
        }
        else
        {
            ui->bedairw->setText("开");
            Static::airf = 1;
        }
    }
    if(key.toInt() == 105)
    {
        if(val.toString() == "0")
        {    ui->bedlight_2->setText("关");
             Static::bedl = 0;
        }
        else
        {
            ui->bedlight_2->setText("开");
            Static::bedl = 1;
        }
    }

    listinit(key.toInt());

}
QString Widget::listinit(int a)
{
//    nodea nod;

    QFile file(":/node.json");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"can't open error";
    }
    QByteArray byteArr = file.readAll(); //文本格式字符串
//    QString jsonStr = QString(byteArr);
    QJsonParseError jerr;
    QJsonDocument doc = QJsonDocument::fromJson(byteArr, &jerr);
    if (doc.isNull())
    {
        qDebug() << jerr.errorString();
    }
    QJsonObject jroot = doc.object();
    QJsonValue Value = jroot.value("m0");   //通过key得到键值
    QJsonObject m0 = Value.toObject();
    QJsonValue dataval = m0.value("data");
    QJsonArray dataArr = dataval.toArray();   //创建json数组

    for(int i=0;i<dataArr.count();i++)
    {
        QJsonValue dataValue = dataArr.at(i);
        QJsonObject valObj = dataValue.toObject();
        QJsonValue Valkey = valObj.value("key");
        if(Valkey.toInt()==a)
        {
            QJsonValue nameval = valObj.value("name");
            name = nameval.toString();

            QJsonValue typeval = valObj.value("type");
            type = typeval.toInt();
           qDebug()<<name<<type;

        }

    }



}

void Widget::controlup(QMQTT::Message message)
{
    qDebug()<<message.topic();
}

void Widget::modeup(QMQTT::Message message)
{

    qDebug()<<message.topic();
}



